<?php

class LinkController extends Controller {

    public $msg = '请求异常';
    const GROUP_USER_SUFFIX = '.LIST';// groupid . info
    public $httpsqs;
    public $userId;
    public $groupId;

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array(''),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform any actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete,update', // we only allow deletion via POST request
        );
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * 先载入专业列表
     * @throws CHttpException
     */
    public function actionIndex() {
        Yii::app()->session->add('user_id',Yii::app()->user->id);
        $entry = Yii::app()->session['school_code'];
        session_write_close();
        if (empty($entry))
            throw new CHttpException(404, 'The requested page does not exist.');

        $school = $this->findCurrentSchool($entry);
        $userMem = array();
        $userMem['school_code'] = $entry;
        $userMem['school_id'] = $school->id;
        $userMem['user_name'] = Yii::app()->user->name;
        Yii::app()->cache->set(Yii::app()->user->id, $userMem);
        $subjects = $this->findCurrentSubjects($school->subjects);
        $this->render('index', array('school' => $school, 'subjects' => $subjects));
        Yii::app()->end();
    }

    /**
     * 消息格式 gid_uid_timestamp_msg
     */
    public function actionReceive() {
        $data = array();
        $data['r'] = 0;
        if (isset($_POST['msg'])) {
            //生成标准格式消息
            if($this->userId === NULL)
                $this->userId = Yii::app()->user->id;
            if($this->groupId === NULL){
                $userMem = Yii::app()->cache->get($this->userId);
                $this->groupId = $userMem['group_id'];
            }
            
            $msg = $this->groupId . '_' . $this->userId . '_' . microtime() . '_' .urlencode($_POST['msg']);
            
            if($this->httpsqs === NULL)
                $this->httpsqs = new httpsqs_link("127.0.0.1", 1218, "linkyou", "utf-8");
            $this->httpsqs->put("msgs_queue", $msg);
            $data['r'] = 1;
        }
        echo CJSON::encode($data);
    }

    public function actionOpen() {
        $data = array();
        $data['r'] = 0;
        $data['msg'] = 'invalid group';
        if (isset($_POST['sub'])) {
            $cache = Yii::app()->cache;
            $userId = Yii::app()->user->id;
            $userMem = $cache->get($userId);
            $groupId = $userMem['school_code'] . $_POST['sub']; //拼装groupId schoolcode + subjectcode
            $userMem['group_id'] = $groupId;
            $cache->set($userId, $userMem);
            $group = $this->loadCurrGroup($groupId);
            $group->online = $group->online + 1;
            $group->people = $group->people + 1;
            $cache->set($groupId, $group);//可能数据并发写，造成错误
            //加入聊天组
            //时间戳设置为0，表示没数据
            $userIds = $cache->get($groupId . self::GROUP_USER_SUFFIX);
            if(empty($userIds))
                $userIds = array();
            $userIds[$userId] = microtime();
            $cache->set($groupId . self::GROUP_USER_SUFFIX, $userIds);
            $data['r'] = 1;
            $data['msg'] = 'success open';
        }
        echo CJSON::encode($data);
    }

    /**
     * 注意清掉所有该用户聊天组信息，缓存等等，并通知阻塞进程结束
     */
    public function actionClose() {
        $data = array();
        $data['r'] = 0;
        $data['msg'] = 'invalid close';
        $cache = Yii::app()->cache;
        $userId = Yii::app()->user-id;
        $userMem = $cache->get($userId);
        $groupId = $userMem['group_id'];
        if (!empty($groupId)) {
            $group = $this->loadCurrGroup($groupId);
            $group->online = $group->online - 1;
            $cache->set($groupId, $group);
            //清除用户在组信息
            $userList = $cache->get($groupId . self::GROUP_USER_SUFFIX);
            foreach ($userList as $key => $value) {
                if($key == $userId){
                    unset($userList[$key]);
                    break;
                }
            }
            $cache->set($groupId . self::GROUP_USER_SUFFIX, $userList);
            $userMem['group_id'] = 0;
            $cache->set($userId, $userMem);
            $data['r'] = 1;
            $data['msg'] = 'close success';
        }
        echo CJSON::encode($data);
    }

    /**
     * 读取数据库group 数据到memcache, 不同于memcache 中的 组消息 key
     * @param type $key
     * @param type $id
     * @return \Chatgroup
     */
    protected function loadCurrGroup($id) {
        $group = Yii::app()->cache->get($id);
        if (empty($group)) {
            //从数据库加载
            $criteria = new CDbCriteria();
            $criteria->condition = 'group_id=' . $id;
            $group = Chatgroup::model()->find($criteria);
            //新建一个group
            if (empty($group)) {
                $group = new Chatgroup();
                $group->group_id = $id;
                if ($group->validate() && $group->save()) {
                    //do nothing
                }
            }
            Yii::app()->cache->set($id, $group);
        }
        return $group;
    }

    protected function findCurrentSchool($entry) {
        $schools = School::model()->loadSchools();
        foreach ($schools as $school) {
            if ($school->code === $entry)
                return $school;
        }
        return NULL;
    }

    /**
     * 1,2,3,4,5,....
     * @param type $subjects
     */
    protected function findCurrentSubjects($subjects) {
        $subIds = explode(',', $subjects);
        $allSubjects = $this->loadSubjects();
        $currSubjects = array();
        foreach ($allSubjects as $singleOne) {
            if (in_array($singleOne->id, $subIds)) {
                $currSubjects[] = $singleOne;
            }
        }
        return $currSubjects;
    }

    protected function loadSubjects() {
        $subjects = Yii::app()->cache->get('subjects');
        if (empty($subjects)) {
            $criteria = new CDbCriteria();
            $criteria->condition = 'status=' . Subject::STATUS_OK;
            $subjects = Subject::model()->findAll($criteria);
            Yii::app()->cache->set('subjects', $subjects);
        }
        return $subjects;
    }
}